<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%
    String username = request.getParameter("username");
    String password = request.getParameter("password");

    // 数据库连接信息
    String url = "jdbc:sqlserver://localhost:1433;databaseName=mydb";
    String dbUsername = "sa";
    String dbPassword = "1";

    // 查询数据库是否存在相应的用户
    boolean isValidUser = false;
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        Connection conn = DriverManager.getConnection(url, dbUsername, dbPassword);
        String query = "SELECT * FROM users WHERE name = ? AND pwd = ?";
        PreparedStatement pstmt = conn.prepareStatement(query);
        pstmt.setString(1, username);
        pstmt.setString(2, password);
        ResultSet rs = pstmt.executeQuery();
        isValidUser = rs.next(); // 如果存在匹配的用户，则返回 true
        conn.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    if(isValidUser) {
        session.setAttribute("adminUsername", username);
        response.sendRedirect("admin_main.jsp");
    } else {
        response.sendRedirect("admin_login.jsp?error=1");
    }
%>
